package com.ddwl.goods.util;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Random;

/**
 * @Author hemiaojun
 * @Date 2020/10/28 10:10
 */
public class BargainCommonUtils {

    public static BigDecimal randomReducePrice(BigDecimal surplusPrice, BigDecimal min, BigDecimal max,Integer rate) {
        Random random = new Random();
        double dMax = max.doubleValue();
        double dMin = min.doubleValue();
        double r = random.nextDouble() *(dMax - dMin) + dMin;
        BigDecimal bargainPrice = new BigDecimal(String.valueOf(r)).setScale(2, RoundingMode.HALF_DOWN);
        if (rate.compareTo(0) > 0) {
            bargainPrice = bargainPrice.multiply(BigDecimal.valueOf(rate));
        }
        if (bargainPrice.compareTo(surplusPrice) > 0) {
            return surplusPrice;
        }
        return bargainPrice;
    }

    /**
     * 随机递减
     */
    public static BigDecimal getReducePrice(BigDecimal leftReduce, int totalReduceTimes, int reducedTimes,int willReducedTimes,int deep){
        if (leftReduce.compareTo(new BigDecimal("0.01")) <= 0) {
            return leftReduce;
        }
        if (deep > 10) {
            return new BigDecimal("0.01");
        }
        BigDecimal cutPrice=BigDecimal.ZERO;
        int alreadyTimes = reducedTimes;
        //最后一刀保证价格准确
        if (totalReduceTimes <= (reducedTimes+willReducedTimes)) {
            return leftReduce;
        } else {
            BigDecimal leftMoney = leftReduce;
            for (int i = 0; i < willReducedTimes; i++) {
                Integer min = (leftMoney).divide(BigDecimal.valueOf(totalReduceTimes).subtract(new BigDecimal(reducedTimes)), 2, BigDecimal.ROUND_UP).multiply(new BigDecimal(100)).intValue();
                //此次砍价的最高钱数（最低价格的2倍）
                //这个倍数越高，砍价的幅度跳动越大。建议设置到1-2.（不能超过2.因为有可到导致总刀数不准确）
                double max = min * 1;
                if (reducedTimes < Math.max(totalReduceTimes / 3, 1)) {
                    max = min * 2;
                } else if (reducedTimes < Math.max(totalReduceTimes / 2, 1)) {
                    max = min * 1.9;
                }
                reducedTimes++;
                //此次砍的价格（最低钱数到最高钱数的随机）
                BigDecimal temp = new BigDecimal(min + new Random().nextDouble() * max).divide(BigDecimal.valueOf(100), 2, BigDecimal.ROUND_UP);
                cutPrice = cutPrice.add(temp);
                leftMoney = leftMoney.subtract(temp);
            }
        }
        BigDecimal returnPrice = cutPrice.compareTo(leftReduce) > 0 ? leftReduce : cutPrice;
        if (alreadyTimes + willReducedTimes < totalReduceTimes && cutPrice.compareTo(leftReduce) >= 0) {
            returnPrice=getReducePrice(leftReduce, totalReduceTimes, alreadyTimes, willReducedTimes,deep++);
        }
        return returnPrice;
    }


}